package cn.laixueit.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

@Service
public class GenerateHtml {

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private GoodsService goodsService;

    @Value("${item.path}")
    private String path;

    @Async
    public void genItemHtml(long spuId){

        Map<String, Object> data = goodsService.loadData(spuId);

        Context context = new Context();
        context.setVariables(data);

        File file = new File(path,spuId+".html");
        FileWriter writer = null;
        try {
            writer = new FileWriter(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        templateEngine.process("item",context,writer);
    }
}
